package com.ydy.service.role.impl;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydy.constant.SystemConstant;
import com.ydy.dto.RelationAdminRoleDTO;
import com.ydy.dto.RelationStaffRoleDTO;
import com.ydy.exception.BusinessException;
import com.ydy.exception.DataNotFoundException;
import com.ydy.exception.ValidateException;
import com.ydy.ienum.EnumRole;
import com.ydy.mapper.RelationAdminRoleMapper;
import com.ydy.mapper.RelationStaffRoleMapper;
import com.ydy.mapper.RoleMapper;
import com.ydy.model.RelationAdminRole;
import com.ydy.model.RelationStaffRole;
import com.ydy.model.Role;
import com.ydy.model.Staff;
import com.ydy.service.admin.AdminService;
import com.ydy.service.role.RoleService;
import com.ydy.service.staff.StaffService;
import com.ydy.utils.ValidateUtil;
import com.ydy.vo.other.BaseVo;
import com.ydy.vo.other.PageVo;
import com.ydy.vo.other.ResultVo;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	private final static Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RelationAdminRoleMapper relationAdminRoleMapper;
	@Autowired
	private RelationStaffRoleMapper relationStaffRoleMapper;
	@Autowired
	private AdminService adminService;
	@Autowired
	private StaffService staffService;

	@Override
	public PageVo<Role> select(Role role, Integer page, Integer size) {
		PageVo<Role> vo = new PageVo<Role>(page, size);
		Page<Role> pageBean = PageHelper.startPage(vo.getPage(), vo.getSize(), "id desc");
		List<Role> list = roleMapper.select(role);
		vo.setTotal(pageBean.getTotal());
		vo.setList(list);
		return vo;
	}

	@Override
	public Role saveOrUpdate(Role role) {
		if (role == null) {
			throw new NullPointerException();
		}
		// 校验数据有效
		Map<String, String> validateInfo = ValidateUtil.validateEntity(role);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		Date now = new Date();
		// 新增信息
		if (role.getId() == null) {
			role.setUseStatus(SystemConstant.USE_STATUS_ON);
			role.setCreateTime(now);
			roleMapper.insertSelective(role);
			log.info("新增role成功：" + role.getId());
		} else {// 根据id更新信息
			Role temp = roleMapper.selectByPrimaryKey(role.getId());
			if (temp == null) {
				log.info("找不到role信息：" + role.getId());
				throw new DataNotFoundException(EnumRole.DATA_NOT_FOUND);
			}
			roleMapper.updateByPrimaryKeySelective(role);
			log.info("更新role成功：" + role.getId());
		}
		return role;
	}

	@Override
	public BaseVo delete(Long id, Staff staff) {
		if (id == null) {
			throw new NullPointerException();
		}
		Role temp = roleMapper.selectByPrimaryKey(id);
		if (temp == null) {
			log.info("找不到role信息：" + id);
			throw new DataNotFoundException(EnumRole.DATA_NOT_FOUND);
		}
		if (staff != null) {
			if (Objects.equals(temp.getShopId(), staff.getShopId())) {
				throw new BusinessException(EnumRole.ROLE_NOT_BELONG_SHOP);
			}
		}
		roleMapper.deleteByPrimaryKey(id);
		log.info("删除role成功：" + id);
		return new ResultVo();
	}

	@Override
	public BaseVo status(Long id, Staff staff) {
		if (id == null) {
			throw new NullPointerException();
		}
		Role temp = roleMapper.selectByPrimaryKey(id);
		if (temp == null) {
			log.info("找不到role信息：" + id);
			throw new DataNotFoundException(EnumRole.DATA_NOT_FOUND);
		}
		if (staff != null) {
			if (Objects.equals(temp.getShopId(), staff.getShopId())) {
				throw new BusinessException(EnumRole.ROLE_NOT_BELONG_SHOP);
			}
		}
		Role role = new Role();
		role.setId(id);
		StringBuilder builder = new StringBuilder();
		if (Objects.equals(SystemConstant.USE_STATUS_ON, temp.getUseStatus())) {
			role.setUseStatus(SystemConstant.USE_STATUS_OFF);
			builder.append("Role不可用成功:").append(id);
		} else {
			role.setUseStatus(SystemConstant.USE_STATUS_ON);
			builder.append("Role可用成功:").append(id);
		}
		roleMapper.updateByPrimaryKeySelective(role);
		log.info(builder.toString());
		return new ResultVo();
	}

	@Override
	public Role selectById(Long id, Staff staff) {
		if (id == null) {
			throw new NullPointerException();
		}
		Role temp = roleMapper.selectByPrimaryKey(id);
		if (temp == null) {
			throw new BusinessException(EnumRole.DATA_NOT_FOUND);
		}
		if (staff != null) {
			if (Objects.equals(temp.getShopId(), staff.getShopId())) {
				throw new BusinessException(EnumRole.ROLE_NOT_BELONG_SHOP);
			}
		}
		return temp;
	}

	@Override
	public List<Role> selectByAdminId(Long adminId) {
		adminService.selectById(adminId);
		return roleMapper.selectByAdminId(adminId);
	}

	@Override
	public List<Role> selectByStaffId(Long staffId) {
		staffService.selectById(staffId);
		return roleMapper.selectByStaffId(staffId);
	}

	@Override
	public BaseVo saveAdminRole(RelationAdminRoleDTO dto) {
		if (dto == null) {
			throw new NullPointerException();
		}
		// 校验数据有效
		Map<String, String> validateInfo = ValidateUtil.validateEntity(dto);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		adminService.selectById(dto.getAdminId());
		RelationAdminRole record = new RelationAdminRole();
		record.setAdminId(dto.getAdminId());
		RelationAdminRole relation = null;
		List<Long> ids = dto.getRoleIds();
		Date now = new Date();
		List<RelationAdminRole> relationList = new LinkedList<RelationAdminRole>();
		for (Long id : ids) {
			relation = new RelationAdminRole();
			relation.setAdminId(dto.getAdminId());
			relation.setRoleId(id);
			relation.setCreateTime(now);
			relationList.add(relation);
		}
		relationAdminRoleMapper.delete(record);
		relationAdminRoleMapper.insertList(relationList);
		return new ResultVo();
	}

	@Override
	public BaseVo saveStaffRole(RelationStaffRoleDTO dto) {
		if (dto == null) {
			throw new NullPointerException();
		}
		// 校验数据有效
		Map<String, String> validateInfo = ValidateUtil.validateEntity(dto);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		staffService.selectById(dto.getStaffId());
		RelationStaffRole record = new RelationStaffRole();
		record.setStaffId(dto.getStaffId());
		RelationStaffRole relation = null;
		List<Long> ids = dto.getRoleIds();
		Date now = new Date();
		List<RelationStaffRole> relationList = new LinkedList<RelationStaffRole>();
		for (Long id : ids) {
			relation = new RelationStaffRole();
			relation.setStaffId(dto.getStaffId());
			relation.setRoleId(id);
			relation.setCreateTime(now);
			relationList.add(relation);
		}
		relationStaffRoleMapper.delete(record);
		relationStaffRoleMapper.insertList(relationList);
		return new ResultVo();
	}

}
